package com.glela.live.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.glela.cache.model.RedisKey;
import com.glela.cache.redis.RedisKeys;
import com.glela.cache.redis.RedisUtil;
import com.glela.live.mapper.LivePlanMapper;
import com.glela.live.messages.LiveDoneMessage;
import com.glela.live.model.LivePlan;
import com.glela.live.model.LiveUserRecord;
import com.glela.live.service.ChatRoomService;
import com.glela.live.service.LivePlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by jinweiwei on 2018/3/2.
 */
@Service
public class LivePlanServiceImpl implements LivePlanService{

    @Autowired
    private LivePlanMapper livePlanMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ChatRoomService chatRoomService;

    @Override
    public LivePlan getById(int id) {
        String data = redisUtil.get(RedisKey.REDIS_KEY_LIVE_PLAN_DETAIL+id);
        if (data==null){
            LivePlan livePlan = livePlanMapper.getById(id);
            if (livePlan!=null){
                redisUtil.set(RedisKey.REDIS_KEY_LIVE_PLAN_DETAIL+id,livePlan);
            }
            return livePlan;
        }
        return JSONObject.parseObject(data,LivePlan.class);
    }

    @Override
    public LivePlan getActiveByLiveUid(int liveUserId) {
        return livePlanMapper.getActiveByLiveUid(liveUserId);
    }

    @Override
    public List<LivePlan> getShowList() {
        return livePlanMapper.getShowList();
    }

    @Override
    public LivePlan getByStartTime(int liveUserId, Date startTime) {
        return livePlanMapper.getByStartTime(liveUserId,startTime);
    }

    @Override
    public int endLiving(String planId) {
        //删除计划列表重新缓存 从缓存获取直播计划的点赞总数更新到liveplan表中，下发消息给聊天室告诉app端直播已经结束
        String likeTotal = redisUtil.get(RedisKeys.LIVE_PLAN_TOTAL_LIKE_NUM+planId);
        int totals = 0;//likeTotal==null?0:Long.valueOf(likeTotal);
        if (likeTotal!=null){
            try {
                totals = Integer.valueOf(likeTotal);
            } catch (NumberFormatException e) {
                totals = Integer.MAX_VALUE;
            }
        }

        int count = livePlanMapper.updatePlanLikeTotal(Integer.valueOf(planId),totals);
        redisUtil.del(RedisKeys.LIVE_PLAN_TOTAL_LIKE_NUM+planId);
        redisUtil.expire(RedisKey.REDIS_KEY_LIVE_PLAN_DETAIL+planId,3600);
        int sendResult = 0;
        int trycount = 0;
        while (true){
            if (sendResult>0 || trycount>2){
                break;
            }else{
                LiveDoneMessage liveDoneMessage = new LiveDoneMessage();
                sendResult = chatRoomService.mngSendMessage(Integer.valueOf(planId),liveDoneMessage);
                trycount++;
            }
        }
        //进入离开直播间写入数据库
        int size = redisUtil.llength(RedisKey.REDIS_KEY_LIVE_PLAN_USER_RECORD+planId).intValue();
        int pages = size/200;
        int batchCount = size%200==0?0:1;
        pages = pages+batchCount;
        for (int i = 0; i < pages; i++) {
            List<String> list = redisUtil.lRang(RedisKey.REDIS_KEY_LIVE_PLAN_USER_RECORD+planId,i*200,(i+1)*200-1);
            if (list!=null && !list.isEmpty()){
                List<LiveUserRecord> userRecords = new ArrayList<LiveUserRecord>(list.size());
                for (String record: list){
                    LiveUserRecord liveUserRecord = JSONObject.parseObject(record,LiveUserRecord.class);
                    userRecords.add(liveUserRecord);
                }
                chatRoomService.addBatchUserRecord(userRecords);
            }
        }

        return count;
    }

	@Override
	public LivePlan getLivePlan() {
		 return livePlanMapper.getLivePlan();
	}
}
